const co = require('co')
const requestPro = require('request-promise-native')
const {
	select,
	selectOne,
	insert,
	insertBatch,
	update,
	executeSQL,
} = require('../db-mysql')
const {
	getProjectById,
} = require('./module-project')
const {
	$UL_API_LOG,
} = require('../../app-logger/logger')

const projectTable = 'tb_project'
const apiDetailTable = 'tb_api_detail'
const apiDetailFields = [
	'project_id',
	'project_data'
]
const projectVersionTable = 'tb_project_version'
const projectVersionFields = [
	'id',
	'version',
	'description',
	'project_data',
	'user_id',
	'project_id',
	'edit_user',
	'modify_date'
]

module.exports = {

	getProjectData(projectId) {
		let SQL = 'SELECT tp.id, tp.name, tp.is_locked, tp.locked_user, tp.version, tp.test_server_url, tad.project_data FROM tb_project tp'
		SQL += ' LEFT JOIN tb_api_detail tad ON tp.id = tad.project_id'
		SQL += ` WHERE tp.id = ${projectId}`
		return selectOne(SQL);
		// return selectOne({
		// 	table: apiDetailTable,
		// 	fields: apiDetailFields,
		// 	where: [
		// 		`project_id = ${projectId}`
		// 	]
		// })
	},

	saveAPI(params) {
		let {
			project_id,
			project_data,
			version,
			user_id,
			edit_user,
			description,
			history_html = '',
			history_json,
			org_project_data,
		} = params
		try {
			history_json = JSON.parse(history_json)
			org_project_data = JSON.parse(org_project_data)
		} catch (e) {
			history_json = {}
			org_project_data = {}
			console.log(e)
		}
		let info = description
		description = {
			info,
			historyHTML: history_html,
			historyJSON: history_json,
			orgProjectData: org_project_data,
		}
		description = JSON.stringify(JSON.stringify(description))
		description = description.replace(/^["'`]|["'`]$/g, '')
		try {
			project_data = JSON.parse(project_data)
			project_data = filterProjectData(project_data);
		} catch (e) {
			console.log(e)
		}
		project_data = JSON.stringify(project_data)
		project_data = project_data.replace(/^["'`]|["'`]$/g, '')
		return co(function*() {
			yield update({
				table: projectTable,
				updates: [`version = '${version}'`, 'is_locked = 0', "locked_user = ''"],
				where: [`id = '${project_id}'`],
			})
			yield update({
				table: apiDetailTable,
				updates: [`project_data = '${project_data}'`],
				where: [`project_id = '${project_id}'`],
			})
			let fields = projectVersionFields.filter(val => {
				if (val == 'id')
					return false
				return true
			});
			return insert({
				table: projectVersionTable,
				fields,
				values: [
					version,
					description,
					project_data,
					user_id,
					project_id,
					edit_user,
					'NOW()'
				]
			});
		})
	},

	testAPI(params) {
		let {
			serverUrl,
			method,
			path,
			contentType,
			req_param_str,
			req_header_str,
		} = params
		let headers = null
		try {
			headers = JSON.parse(req_header_str)
		} catch (e) {
			headers = {}
		}
		let options = {
			baseUrl: serverUrl,
			url: path,
			method,
			headers,
		}
		let requestParams = JSON.parse(req_param_str)
		if (contentType == 'application/x-www-form-urlencoded') {
			options.form = requestParams
		} else if (contentType == 'application/json') {
			options.json = requestParams
		} else {
			options.headers['Content-Type'] = contentType
			options.body = req_param_str
		}
		$UL_API_LOG(`测试请求参数 ===>>> ${JSON.stringify(options)}`)
		return requestPro(options)
	},

	/**
	 * 导出api保存为markdown文档
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	exportApi: async function(params) {

		return '# 1.AAA '

	},

}

/**
 * 处理接口数据
 * @param  {[type]} projectData [description]
 * @return {[type]}             [description]
 */
function filterProjectData(projectData) {
	projectData.treeData = projectData.treeData.map(val => {
		let newVal = {
			id: val.id,
			text: val.text,
		}
		if (val.children) {
			newVal.state = 'closed'
			newVal.children = filterChildren(val.children)
		}
		return newVal
	})
	return JSON.stringify(projectData)
}

function filterChildren(children) {
	let cArr = []
	for (let i = 0; i < children.length; i++) {
		let node = children[i]
		let newNode = {
			id: node.id,
			text: node.text,
		}
		if (node.children) {
			newNode.state = 'closed'
			newNode.children = filterChildren(node.children)
		}
		cArr.push(newNode)
	}
	return cArr
}